package com.engine.salary.sys.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.api.formmode.mybatis.util.SqlProxyHandle;
import com.cloudstore.dev.api.util.Util_DataCache;
import com.engine.common.util.ServiceUtil;
import com.engine.core.impl.Service;
import com.engine.salary.encrypt.AESEncryptUtil;
import com.engine.salary.encrypt.EncryptUtil;
import com.engine.salary.entity.datacollection.AddUpDeduction;
import com.engine.salary.entity.datacollection.AddUpSituation;
import com.engine.salary.entity.datacollection.po.OtherDeductionPO;
import com.engine.salary.entity.datacollection.po.SpecialAddDeductionPO;
import com.engine.salary.entity.datacollection.po.VariableArchiveItemPO;
import com.engine.salary.entity.salaryacct.po.ExcelAcctResultPO;
import com.engine.salary.entity.salaryacct.po.SalaryAcctResultPO;
import com.engine.salary.entity.salaryarchive.po.SalaryArchiveItemPO;
import com.engine.salary.entity.siaccount.po.ExcelInsuranceDetailPO;
import com.engine.salary.entity.siaccount.po.InsuranceAccountBatchPO;
import com.engine.salary.entity.siaccount.po.InsuranceAccountDetailPO;
import com.engine.salary.entity.siarchives.po.InsuranceArchivesFundSchemePO;
import com.engine.salary.entity.siarchives.po.InsuranceArchivesOtherSchemePO;
import com.engine.salary.entity.siarchives.po.InsuranceArchivesSocialSchemePO;
import com.engine.salary.entity.sischeme.po.InsuranceSchemeDetailPO;
import com.engine.salary.entity.taxdeclaration.po.TaxDeclarationDetailPO;
import com.engine.salary.exception.SalaryRunTimeException;
import com.engine.salary.mapper.archive.SalaryArchiveItemMapper;
import com.engine.salary.mapper.datacollection.*;
import com.engine.salary.mapper.salaryacct.ExcelAcctResultMapper;
import com.engine.salary.mapper.salaryacct.SalaryAcctResultMapper;
import com.engine.salary.mapper.siaccount.ExcelInsuranceDetailMapper;
import com.engine.salary.mapper.siaccount.InsuranceAccountBatchMapper;
import com.engine.salary.mapper.siaccount.InsuranceAccountDetailMapper;
import com.engine.salary.mapper.siarchives.FundSchemeMapper;
import com.engine.salary.mapper.siarchives.OtherSchemeMapper;
import com.engine.salary.mapper.siarchives.SocialSchemeMapper;
import com.engine.salary.mapper.sischeme.InsuranceSchemeDetailMapper;
import com.engine.salary.mapper.sys.SalarySysConfMapper;
import com.engine.salary.mapper.taxdeclaration.TaxDeclarationDetailMapper;
import com.engine.salary.service.VariableArchiveItemService;
import com.engine.salary.service.impl.VariableArchiveItemServiceImpl;
import com.engine.salary.sys.config.SysConfig;
import com.engine.salary.sys.constant.SalarySysConstant;
import com.engine.salary.sys.entity.param.AppSettingSaveParam;
import com.engine.salary.sys.entity.param.OrderRuleParam;
import com.engine.salary.sys.entity.po.SalarySysConfPO;
import com.engine.salary.sys.entity.vo.AppSettingVO;
import com.engine.salary.sys.entity.vo.OrderRuleVO;
import com.engine.salary.sys.entity.vo.UploadConfigResponse;
import com.engine.salary.sys.enums.*;
import com.engine.salary.sys.service.SalarySysConfService;
import com.engine.salary.util.SalaryEntityUtil;
import com.engine.salary.util.db.IdGenerator;
import com.engine.salary.util.db.MapperProxyFactory;
import com.google.common.collect.Lists;
import com.weaver.util.threadPool.ThreadPoolUtil;
import com.weaver.util.threadPool.constant.ModulePoolEnum;
import com.weaver.util.threadPool.entity.LocalRunnable;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;
import weaver.conn.mybatis.MyBatisFactory;
import weaver.general.BaseBean;
import weaver.hrm.User;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

import static com.engine.salary.sys.constant.SalarySysConstant.*;
import static java.util.concurrent.Executors.newFixedThreadPool;

/**
 * 薪酬系统配置类
 * <p>Copyright: Copyright (c) 2022</p>
 * <p>Company: 泛微软件</p>
 *
 * @author qiantao
 * @version 1.0
 **/
@Slf4j
public class SalarySysConfServiceImpl extends Service implements SalarySysConfService {

    private static volatile Boolean encryptStatus = null;

    private EncryptUtil encryptUtil = new EncryptUtil();

    private SalarySysConfMapper getSalarySysConfMapper() {
        return SqlProxyHandle.getProxy(SalarySysConfMapper.class);
    }

    private static final ExecutorService fixedThreadPool = newFixedThreadPool(3);

    private SalaryAcctResultMapper getSalaryAcctResultMapper() {
        return MapperProxyFactory.getProxy(SalaryAcctResultMapper.class);
    }

    private ExcelAcctResultMapper getExcelAcctResultMapper() {
        return MapperProxyFactory.getProxy(ExcelAcctResultMapper.class);
    }

    private TaxDeclarationDetailMapper getTaxDeclarationDetailMapper() {
        return MapperProxyFactory.getProxy(TaxDeclarationDetailMapper.class);
    }

    private InsuranceSchemeDetailMapper getInsuranceSchemeDetailMapper() {
        return MapperProxyFactory.getProxy(InsuranceSchemeDetailMapper.class);
    }

    private SocialSchemeMapper getSocialSchemeMapper() {
        return MapperProxyFactory.getProxy(SocialSchemeMapper.class);
    }

    private FundSchemeMapper getFundSchemeMapper() {
        return MapperProxyFactory.getProxy(FundSchemeMapper.class);
    }

    private OtherSchemeMapper getOtherSchemeMapper() {
        return MapperProxyFactory.getProxy(OtherSchemeMapper.class);
    }

    private InsuranceAccountBatchMapper getInsuranceAccountBatchMapper() {
        return MapperProxyFactory.getProxy(InsuranceAccountBatchMapper.class);
    }

    private InsuranceAccountDetailMapper getInsuranceAccountDetailMapper() {
        return MapperProxyFactory.getProxy(InsuranceAccountDetailMapper.class);
    }

    private SalaryArchiveItemMapper getSalaryArchiveItemMapper() {
        return MapperProxyFactory.getProxy(SalaryArchiveItemMapper.class);
    }

    private AddUpDeductionMapper getAddUpDeductionMapper() {
        return MapperProxyFactory.getProxy(AddUpDeductionMapper.class);
    }

    private OtherDeductionMapper getOtherDeductionMapper() {
        return MapperProxyFactory.getProxy(OtherDeductionMapper.class);
    }

    private AddUpSituationMapper getAddUpSituationMapper() {
        return MapperProxyFactory.getProxy(AddUpSituationMapper.class);
    }

    private SpecialAddDeductionMapper getSpecialAddDeductionMapper() {
        return MapperProxyFactory.getProxy(SpecialAddDeductionMapper.class);
    }

    private ExcelInsuranceDetailMapper getExcelInsuranceDetailMapper() {
        return MapperProxyFactory.getProxy(ExcelInsuranceDetailMapper.class);
    }

    private SalarySysConfService getSalarySysConfService(User user) {
        return ServiceUtil.getService(SalarySysConfServiceImpl.class, user);
    }

    private VariableArchiveItemService getVariableArchiveItemService(User user) {
        return ServiceUtil.getService(VariableArchiveItemServiceImpl.class, user);
    }

    /**
     * 操作是否需要申报功能
     *
     * @param flag 开启 0/关闭 1/重新开启 2
     * @return 执行结果
     */
    @Override
    public boolean operateTaxDeclarationFunction(TaxDeclarationFunctionEnum flag) {
        Date date = new Date();
        SalarySysConfPO taxDeclarationFunction = getSalarySysConfMapper().getOneByCode(TAX_DECLARATION_FUNCTION);
        if (taxDeclarationFunction == null) {
            taxDeclarationFunction = SalarySysConfPO.builder().id(IdGenerator.generate()).confKey(TAX_DECLARATION_FUNCTION).confValue(flag.getValue()).title(flag.getDefaultLabel()).module("taxDeclaration").orderWeight(0).createTime(date).updateTime(date).deleteType(0).build();
            getSalarySysConfMapper().insertIgnoreNull(taxDeclarationFunction);
        } else {
            TaxDeclarationFunctionEnum oldFunctionEnum = TaxDeclarationFunctionEnum.parseByValue(taxDeclarationFunction.getConfValue());
            //不改变
            if (flag == oldFunctionEnum) {
                return true;
            }
            //关闭
            if (flag == TaxDeclarationFunctionEnum.CLOSURE) {
                taxDeclarationFunction.setConfValue(flag.getValue());
                taxDeclarationFunction.setTitle(flag.getDefaultLabel());
                taxDeclarationFunction.setUpdateTime(new Date());
            }
            //重启 (从关闭到开启)
            if (flag == TaxDeclarationFunctionEnum.OPEN && oldFunctionEnum == TaxDeclarationFunctionEnum.CLOSURE) {
                taxDeclarationFunction.setConfValue(TaxDeclarationFunctionEnum.REBOOT.getValue());
                taxDeclarationFunction.setTitle(TaxDeclarationFunctionEnum.REBOOT.getDefaultLabel());
                taxDeclarationFunction.setUpdateTime(new Date());
            }
            getSalarySysConfMapper().updateIgnoreNull(taxDeclarationFunction);
        }
        return true;
    }

    /**
     * @return Boolean
     * @description 获取申报功能状态
     * @author Harryxzy
     * @date 2022/11/7 17:05
     */
    public TaxDeclarationFunctionEnum getTaxDeclaration() {
        SalarySysConfPO taxDeclarationFunction = getOneByCode(TAX_DECLARATION_FUNCTION);
        if (taxDeclarationFunction == null) {
            // 默认开启
            return TaxDeclarationFunctionEnum.OPEN;
        }
        TaxDeclarationFunctionEnum taxDeclarationFunctionEnum = TaxDeclarationFunctionEnum.parseByValue(taxDeclarationFunction.getConfValue());
        return taxDeclarationFunctionEnum;
    }


    @Override
    public SalarySysConfPO getOneByCode(String code) {
        return getSalarySysConfMapper().getOneByCode(code);
    }

    @Override
    public String getValueByCode(String code) {
        SalarySysConfPO confPO = getSalarySysConfMapper().getOneByCode(code);
        return confPO == null ? "" : confPO.getConfValue();
    }

    @Override
    public List<SalarySysConfPO> listSome(SalarySysConfPO po) {
        return getSalarySysConfMapper().listSome(po);
    }

    @Override
    public void save(SalarySysConfPO salarySysConfPO) {
        salarySysConfPO.setId(IdGenerator.generate());
        salarySysConfPO.setUpdateTime(new Date());
        salarySysConfPO.setCreateTime(new Date());
        salarySysConfPO.setDeleteType(0);
        salarySysConfPO.setOrderWeight(0);
        salarySysConfPO.setModule(CUSTOM_CODE);

        getSalarySysConfMapper().insertIgnoreNull(salarySysConfPO);
    }

    @Override
    public void update(SalarySysConfPO salarySysConfPO) {
        SalarySysConfPO po = getSalarySysConfMapper().getById(salarySysConfPO.getId());
        if (po == null) {
            throw new SalaryRunTimeException("系统配置不存在");
        }
        salarySysConfPO.setUpdateTime(new Date());
        getSalarySysConfMapper().updateIgnoreNull(salarySysConfPO);
    }

    @Override
    public SalarySysConfPO getById(Long id) {
        SalarySysConfPO po = getSalarySysConfMapper().getById(id);
        if (po == null) {
            throw new SalaryRunTimeException("系统配置不存在");
        }
        return po;
    }

    @Override
    public void updateByCode(SalarySysConfPO po) {
        SalarySysConfPO sysConfPO = getSalarySysConfMapper().getOneByCode(po.getConfKey());
        if (sysConfPO == null) {
            throw new SalaryRunTimeException("系统配置不存在");
        }
        sysConfPO.setConfValue(po.getConfValue());
        sysConfPO.setUpdateTime(new Date());
        getSalarySysConfMapper().updateIgnoreNull(sysConfPO);

    }

    @Override
    public OrderRuleVO orderRule() {
        SalarySysConfPO rulePO = getSalarySysConfMapper().getOneByCode(ORDER_RULE_CODE);
        SalarySysConfPO orderPO = getSalarySysConfMapper().getOneByCode(ASCORDESC_CODE);
        OrderRuleVO orderRuleVO = OrderRuleVO.builder().build();
        if (rulePO == null) {
            orderRuleVO.setOrderRule(OrderRuleEnum.DSPORDER.getValue());
        } else {
            orderRuleVO.setOrderRule(OrderRuleEnum.parseByValue(rulePO.getConfValue()).getValue());
        }
        if (orderPO == null) {
            orderRuleVO.setAscOrDesc(AscOrDescEnum.ASC.getValue());
        } else {
            orderRuleVO.setAscOrDesc(AscOrDescEnum.parseByValue(orderPO.getConfValue()).getValue());
        }
        return orderRuleVO;
    }

    @Override
    public void updateOrderRule(OrderRuleParam param) {
        if (param == null || OrderRuleEnum.parseByValue(param.getOrderRule()) == null || AscOrDescEnum.parseByValue(param.getAscOrDesc()) == null) {
            throw new SalaryRunTimeException("配置内容异常！");
        }

        //更新排序规则
        SalarySysConfPO orderRulePo = getSalarySysConfMapper().getOneByCode(ORDER_RULE_CODE);
        if (orderRulePo == null) {
            SalarySysConfPO build = SalarySysConfPO.builder()
                    .id(IdGenerator.generate())
                    .confKey(ORDER_RULE_CODE)
                    .confValue(param.getOrderRule())
                    .title("排序规则")
                    .orderWeight(0)
                    .module("basic")
                    .updateTime(new Date())
                    .createTime(new Date())
                    .deleteType(0)
                    .build();
            getSalarySysConfMapper().insertIgnoreNull(build);
        } else {
            orderRulePo.setConfValue(param.getOrderRule());
            orderRulePo.setUpdateTime(new Date());
            getSalarySysConfMapper().updateIgnoreNull(orderRulePo);
        }

        //更新顺序配置
        SalarySysConfPO ascOrDescPo = getSalarySysConfMapper().getOneByCode(ASCORDESC_CODE);
        if (ascOrDescPo == null) {
            SalarySysConfPO build = SalarySysConfPO.builder()
                    .id(IdGenerator.generate())
                    .confKey(ASCORDESC_CODE)
                    .confValue(param.getAscOrDesc())
                    .title("排序顺序")
                    .orderWeight(0)
                    .module("basic")
                    .updateTime(new Date())
                    .createTime(new Date())
                    .deleteType(0)
                    .build();
            getSalarySysConfMapper().insertIgnoreNull(build);
        } else {
            ascOrDescPo.setConfValue(param.getAscOrDesc());
            ascOrDescPo.setUpdateTime(new Date());
            getSalarySysConfMapper().updateIgnoreNull(ascOrDescPo);
        }
    }

    @Override
    public void saveMatchEmployeeModeRule(String rule) {
        if (MatchEmployeeModeEnum.parseByValue(rule) == null) {
            throw new SalaryRunTimeException("无效规则！");
        }

        saveSettingByType(rule, MATCH_EMPLOYEE_MODE, "定位人员规则", "basic");
    }

    @Override
    public void saveAppSetting(AppSettingSaveParam param) {
        String openAcctResultSum = param.getOpenAcctResultSum();
        saveSettingByType(openAcctResultSum, OPEN_ACCT_RESULT_SUM, "开启核算结果合并", "app");
        saveSettingByType(param.getDisplayEmpInfoReport(), DISPLAY_EMP_INFO_REPORT, "是否显示脱敏表人员信息", "app");
    }

    @Override
    public Map<String, Object> saveEncryptSetting(AppSettingSaveParam param) {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("isSuccess", true);
        String progressId = UUID.randomUUID().toString();
        resultMap.put("progressId", progressId);
        SalarySysConfPO sysConfPo = getOneByCode(SalarySysConstant.OPEN_APPLICATION_ENCRYPT);
        if (sysConfPo != null && sysConfPo.getConfValue().equals(param.getIsOpenEncrypt())) {
            return resultMap;
        } else if (sysConfPo == null && OpenEnum.OPEN.getValue().equals(param.getIsOpenEncrypt())) {
            return resultMap;
        }
        try {
            if (Util_DataCache.getObjVal(AES_ENCRYPT_IN_PROGRESS) != null) {
                resultMap.put("msg", "数据库处理上次操作中，请稍后操作。");
                return resultMap;
            }
            Util_DataCache.setObjVal(AES_ENCRYPT_IN_PROGRESS, 1);
            Util_DataCache.setObjVal(ENCRYPT_IN_PROGRESS + progressId, "in_progress");
            String isOpenEncrypt = param.getIsOpenEncrypt();
            if (StringUtils.isNotEmpty(isOpenEncrypt)) {
                if (isOpenEncrypt.equals(OpenEnum.OPEN.getValue())) {
                    //对数据库数据加解密
                    ThreadPoolUtil.fixedPoolExecute(ModulePoolEnum.erkai, "saveEncryptSetting", new LocalRunnable() {
                        @Override
                        public void execute() {
                            updateEncrypt(isOpenEncrypt);
                            Boolean aBoolean = encryptOrDecryptDbWithAsync(isOpenEncrypt, progressId);
                        }
                    });
                } else if (isOpenEncrypt.equals(OpenEnum.OFF.getValue())) {
                    ThreadPoolUtil.fixedPoolExecute(ModulePoolEnum.erkai, "saveEncryptSetting", new LocalRunnable() {
                        @Override
                        public void execute() {
                            Boolean aBoolean = encryptOrDecryptDbWithAsync(isOpenEncrypt, progressId);
                            updateEncrypt(isOpenEncrypt);
                        }
                    });
                    //不要调换方法的位置
                }
            }
            Util_DataCache.clearVal(AES_ENCRYPT_IN_PROGRESS);
            resultMap.put("isSuccess", true);
            return resultMap;
        } catch (Exception e) {
            Util_DataCache.clearVal(AES_ENCRYPT_IN_PROGRESS);
            resultMap.put("isSuccess", false);
            resultMap.put("msg", "系统异常请联系管理员");
            return resultMap;
        }
    }

    @Override
    public boolean encryptIsOpen() {
        if (encryptStatus == null) {
            SalarySysConfPO sysConfPo = getOneByCode(SalarySysConstant.OPEN_APPLICATION_ENCRYPT);
            if (sysConfPo != null && sysConfPo.getConfValue().equals(OpenEnum.OFF.getValue())) {
                encryptStatus = false;
            } else {
                encryptStatus = true;
            }
        }
        return encryptStatus;
    }

    @Override
    public void cleanEncryptStatus() {
        encryptStatus = null;
    }


    @Override
    public Map<String, Object> getEncryptProgress(String progressId) {
        Map<String, Object> resultMap = new HashMap<>();
        String progressStatue = (String) Util_DataCache.getObjVal(ENCRYPT_IN_PROGRESS + progressId);
        if (StringUtils.isNotEmpty(progressStatue)) {
            resultMap.put("progress_statue", progressStatue);
        } else {
            resultMap.put("progress_statue", "success");
        }
        return resultMap;
    }

    @Override
    public Date getTaxDeclarationRebootDate() {
        Date date = getSalarySysConfMapper().getTaxDeclarationRebootDate();
        return date;
    }

    @Override
    public void saveSalaryAcctEmployeeRule(String rule) {
        if (MatchEmployeeModeEnum.parseByValue(rule) == null) {
            throw new SalaryRunTimeException("无效规则！");
        }

        saveSettingByType(rule, SALARY_ACCT_EMPLOYEE_RULE, "薪资、社保福利核算包含人员规则", "basic");
    }

    @Override
    public void saveWithDrawTaxDeclaration(SalarySysConfPO param) {
        if (StringUtils.isBlank(param.getConfValue())) {
            throw new SalaryRunTimeException("无效规则！");
        }
        saveSettingByType(param.getConfValue(), WITHDRAW_TAX_DECLARATION, "个税申报撤回", "basic");
    }

    @Override
    public void saveArchiveDelete(String setting) {
        if (StringUtils.isBlank(setting)) {
            throw new SalaryRunTimeException("无效规则！");
        }
        saveSettingByType(setting, SALARY_ARCHIVE_DELETE, "薪资、社保福利档案删除规则", "basic");
    }

    @Override
    public void operate(SalarySysConfPO salarySysConfPO) {
        saveSettingByType(salarySysConfPO.getConfValue(), salarySysConfPO.getConfKey(), salarySysConfPO.getTitle(), salarySysConfPO.getModule());
    }

    @Override
    public void saveSalarySendFeedback(SalarySysConfPO param) {
        if (StringUtils.isBlank(param.getConfValue())) {
            throw new SalaryRunTimeException("无效规则！");
        }
        saveSettingByType(param.getConfValue(), SALARY_SEND_FEEDBACK, "工资单反馈", "basic");
    }

    @Override
    public List<SalarySysConfPO> getListByCodes(List<String> codes) {
        if (CollectionUtils.isEmpty(codes)) {
            return Collections.emptyList();
        }
        return getSalarySysConfMapper().getListByCodes(codes);
    }

    /**
     * 保存或者修改应用设置
     *
     * @param confValue
     * @param confKey
     * @param title
     * @param app
     */
    @Override
    public void saveSettingByType(String confValue, String confKey, String title, String app) {
        SalarySysConfPO po = getOneByCode(confKey);
        if (po == null) {
            SalarySysConfPO build = SalarySysConfPO.builder()
                    .id(IdGenerator.generate())
                    .confKey(confKey)
                    .confValue(confValue)
                    .title(title)
                    .orderWeight(0)
                    .module(app)
                    .updateTime(new Date())
                    .createTime(new Date())
                    .deleteType(0)
                    .build();
            getSalarySysConfMapper().insertIgnoreNull(build);
        } else {
            po.setConfValue(confValue);
            po.setUpdateTime(new Date());
            getSalarySysConfMapper().updateIgnoreNull(po);
        }
    }

    @Override
    public SysConfig getConfig() {
        SysConfig sysConfig = new SysConfig();
        List<SalarySysConfPO> salarySysConfPOS = getSalarySysConfMapper().listAll();
        //去除加密配置
        salarySysConfPOS = salarySysConfPOS.stream().filter(po -> !po.getConfKey().equals(OPEN_APPLICATION_ENCRYPT)).collect(Collectors.toList());
        sysConfig.setSalarySysConfs(salarySysConfPOS);
        return sysConfig;
    }

    @Override
    public UploadConfigResponse.Result parseConfig(SysConfig config) {
        UploadConfigResponse.Result result = UploadConfigResponse.Result.builder()
                .message("系统配置加载完毕")
                .success(new ArrayList<>())
                .warning(new ArrayList<>())
                .error(new ArrayList<>())
                .build();

        List<SalarySysConfPO> salarySysConfs = config.getSalarySysConfs();
        if (CollectionUtil.isNotEmpty((salarySysConfs))) {

            salarySysConfs.forEach(po -> {
                try {
                    SalarySysConfPO sysConfPO = getSalarySysConfMapper().getOneByCode(po.getConfKey());
                    if (sysConfPO == null) {
                        po.setId(IdGenerator.generate());
                        getSalarySysConfMapper().insertIgnoreNull(po);
                    } else {
                        sysConfPO.setConfValue(po.getConfValue());
                        getSalarySysConfMapper().updateIgnoreNull(sysConfPO);
                    }
                    result.getSuccess().add(String.format("[%s]配置，key:[%s],value:[%s]", po.getTitle(), po.getConfKey(), po.getConfValue()));
                } catch (Exception e) {
                    log.error(String.format("错误,[%s]配置加载异常，key:[%s],value:[%s]", po.getTitle(), po.getConfKey(), po.getConfValue()), e);
                    result.getError().add(String.format("错误,[%s]配置加载异常，key:[%s],value:[%s],原因：%s", po.getTitle(), po.getConfKey(), po.getConfValue(), e.getMessage()));
                }
            });
        }

        return result;
    }

    /**
     * 开启/关闭加解密
     *
     * @param confValue
     */
    public void updateEncrypt(String confValue) {
        SalarySysConfPO po = getOneByCode(OPEN_APPLICATION_ENCRYPT);
        String title = "1".equals(confValue) ? "开启加密设置" : "关闭加密设置";
        if (po == null) {
            SalarySysConfPO build = SalarySysConfPO.builder()
                    .id(IdGenerator.generate())
                    .confKey(OPEN_APPLICATION_ENCRYPT)
                    .confValue(confValue)
                    .title(title)
                    .orderWeight(0)
                    .module("app")
                    .updateTime(new Date())
                    .createTime(new Date())
                    .deleteType(0)
                    .build();
            getSalarySysConfMapper().insertIgnoreNull(build);
        } else {
            po.setConfValue(confValue);
            po.setTitle(title);
            po.setUpdateTime(new Date());
            getSalarySysConfMapper().updateIgnoreNull(po);
        }
        //重新获取加解密
        cleanEncryptStatus();
    }

    @Override
    public AppSettingVO appSetting() {
        AppSettingVO appSettingVO = AppSettingVO.builder().build();
        //返回按钮状态
        SalarySysConfPO condition = new SalarySysConfPO();
        condition.setDeleteType(0);
        List<SalarySysConfPO> salarySysConfPOS = getSalarySysConfMapper().listSome(condition);
        if (CollectionUtils.isNotEmpty(salarySysConfPOS)) {
            salarySysConfPOS.forEach(salarySysConfPO -> {
                switch (salarySysConfPO.getConfKey()) {
                    case OPEN_ACCT_RESULT_SUM:
                        appSettingVO.setOpenAcctResultSum(salarySysConfPO.getConfValue());
                        break;
                    case OPEN_APPLICATION_ENCRYPT:
                        appSettingVO.setIsOpenEncrypt(salarySysConfPO.getConfValue());
                        break;
                    case DISPLAY_EMP_INFO_REPORT:
                        appSettingVO.setDisplayEmpInfoReport(salarySysConfPO.getConfValue());
                        break;
                    default:
                        break;
                }
            });
        }

        Map<String, SalarySysConfPO> salarySysConfMap = SalaryEntityUtil.convert2Map(salarySysConfPOS, SalarySysConfPO::getConfKey);
        SalarySysConfPO taxDeclarationFunction = salarySysConfMap.get(TAX_DECLARATION_FUNCTION);
        if (taxDeclarationFunction == null || (taxDeclarationFunction.getConfValue().equals(TaxDeclarationFunctionEnum.REBOOT.getValue()))) {
            // 默认开启报税功能 或者重启状态时前端展示开启
            appSettingVO.setIsOpenTaxDeclaration("1");
        } else {
            appSettingVO.setIsOpenTaxDeclaration(taxDeclarationFunction.getConfValue());
        }

        SalarySysConfPO salaryAcctEmployeeRule = salarySysConfMap.get(SALARY_ACCT_EMPLOYEE_RULE);
        if (salaryAcctEmployeeRule == null) {
            // 薪资核算人员匹配规则
            appSettingVO.setSalaryAcctEmployeeRule(SalaryAcctEmployeeRuleEnum.BYPAYENDTIME.getValue());
        } else {
            appSettingVO.setSalaryAcctEmployeeRule(SalaryAcctEmployeeRuleEnum.parseByValue(salaryAcctEmployeeRule.getConfValue()).getValue());
        }

        SalarySysConfPO withDrawRule = salarySysConfMap.get(WITHDRAW_TAX_DECLARATION);
        if (withDrawRule == null) {
            // 个税申报撤回
            appSettingVO.setWithDrawTaxDeclaration("0");
        } else {
            appSettingVO.setWithDrawTaxDeclaration(withDrawRule.getConfValue());
        }

        SalarySysConfPO salaryArchiveDeletePO = salarySysConfMap.get(SALARY_ARCHIVE_DELETE);
        if (salaryArchiveDeletePO == null) {
            // 是否允许删除薪资、社保档案，默认不允许删除
            appSettingVO.setSalaryArchiveDelete("0");
        } else {
            appSettingVO.setSalaryArchiveDelete(salaryArchiveDeletePO.getConfValue());
        }


        SalarySysConfPO salarySendFeedbackPO = salarySysConfMap.get(SALARY_SEND_FEEDBACK);
        if (salarySendFeedbackPO == null) {
            // 是否开启工资单反馈，默认不开启
            appSettingVO.setSalarySendFeedback("0");
        } else {
            appSettingVO.setSalarySendFeedback(salarySendFeedbackPO.getConfValue());
        }

        //默认加密开启
        if (StringUtils.isEmpty(appSettingVO.getIsOpenEncrypt())) {
            appSettingVO.setIsOpenEncrypt(OpenEnum.OPEN.getValue());
        }

        //是否显示脱敏表人员信息
        if (StringUtils.isEmpty(appSettingVO.getDisplayEmpInfoReport())) {
            appSettingVO.setDisplayEmpInfoReport(OpenEnum.OFF.getValue());
        }

        BaseBean baseBean = new BaseBean();
        //是否打印
        String log = baseBean.getPropValue("hrmSalary", "log");
        appSettingVO.setIsLog(log);
        //当前版本号
        String version = baseBean.getPropValue("hrmSalary", "version");
        appSettingVO.setVersion(version);
        //是否开启了强制修改公式
        String openFormulaForcedEditing = baseBean.getPropValue("hrmSalary", "openFormulaForcedEditing");
        appSettingVO.setOpenFormulaForcedEditing(openFormulaForcedEditing);
        //是否显示加解密操作按钮
        String showEncryptOperationButton = baseBean.getPropValue("hrmSalary", "showEncryptOperationButton");
        appSettingVO.setShowEncryptOperationButton(showEncryptOperationButton);

        return appSettingVO;
    }

    private Boolean encryptOrDecryptDbWithAsync(String isOpenEncrypt, String progressId) {
        log.info("应用设置加解密数据开始");
        Util_DataCache.setObjVal(ENCRYPT_IN_PROGRESS + progressId, "in_progress");
        //多线程批量更新需要加密的表
        try {
            SalarySysConfPO sysConfPo = getSalarySysConfService(user).getOneByCode(SalarySysConstant.OPEN_APPLICATION_ENCRYPT);
            Future<Integer> submit = fixedThreadPool.submit(() -> {
                SqlSession sqlSession = MyBatisFactory.sqlSessionFactory.openSession();
                try {
                    List<SalaryAcctResultPO> salaryAcctResultPos = getSalaryAcctResultMapper().listAll();
                    if (CollectionUtils.isNotEmpty(salaryAcctResultPos)) {
                        salaryAcctResultPos.forEach(po -> {
                            if (OpenEnum.OFF.getValue().equals(isOpenEncrypt)) {
                                po.setResultValue(AESEncryptUtil.closeEncryptSetting(po.getResultValue(), sysConfPo));
                                po.setOriginResultValue(AESEncryptUtil.closeEncryptSetting(po.getOriginResultValue(), sysConfPo));
                            } else {
                                po.setResultValue(AESEncryptUtil.encrypt(po.getResultValue()));
                                po.setOriginResultValue(AESEncryptUtil.encrypt(po.getOriginResultValue()));
                            }
                        });
                        List<List<SalaryAcctResultPO>> partition = Lists.partition(salaryAcctResultPos, 50);
                        SalaryAcctResultMapper mapper = sqlSession.getMapper(SalaryAcctResultMapper.class);
                        partition.forEach(mapper::batchUpdate);
                        sqlSession.commit();
                        log.info("finish hrsa_salary_acct_result");
                    }
                } catch (Exception e) {
                    sqlSession.rollback();
                    log.error("fail hrsa_salary_acct_result", e);
                    return 0;
                } finally {
                    sqlSession.close();
                }
                return 1;
            });
            Future<Integer> submit1 = fixedThreadPool.submit(() -> {
                SqlSession sqlSession = MyBatisFactory.sqlSessionFactory.openSession();
                try {
                    List<ExcelAcctResultPO> excelAcctResultPos = getExcelAcctResultMapper().listSome(new ExcelAcctResultPO());
                    if (CollectionUtils.isNotEmpty(excelAcctResultPos)) {
                        excelAcctResultPos.forEach(po -> {
                            if (OpenEnum.OFF.getValue().equals(isOpenEncrypt)) {
                                po.setResultValue(AESEncryptUtil.closeEncryptSetting(po.getResultValue(), sysConfPo));
                            } else {
                                po.setResultValue(AESEncryptUtil.encrypt(po.getResultValue()));
                            }
                        });
                        List<List<ExcelAcctResultPO>> partition = Lists.partition(excelAcctResultPos, 50);
                        ExcelAcctResultMapper mapper = sqlSession.getMapper(ExcelAcctResultMapper.class);
                        partition.forEach(mapper::batchUpdate);
                        log.info("finish hrsa_excel_acct_result");
                        sqlSession.commit();
                    }
                } catch (Exception e) {
                    sqlSession.rollback();
                    log.error("fail hrsa_excel_acct_result", e);
                    return 0;
                } finally {
                    sqlSession.close();
                }
                return 1;
            });
            Future<Integer> submit2 = fixedThreadPool.submit(() -> {
                SqlSession sqlSession = MyBatisFactory.sqlSessionFactory.openSession();
                try {
                    List<TaxDeclarationDetailPO> taxDeclarationDetailPos = getTaxDeclarationDetailMapper().listAll();
                    if (CollectionUtils.isNotEmpty(taxDeclarationDetailPos)) {
                        taxDeclarationDetailPos.forEach(po -> {
                            if (OpenEnum.OFF.getValue().equals(isOpenEncrypt)) {
                                po.setFieldValue(AESEncryptUtil.closeEncryptSetting(po.getFieldValue(), sysConfPo));
                            } else {
                                po.setFieldValue(AESEncryptUtil.encrypt(po.getFieldValue()));
                            }
                        });
                        List<List<TaxDeclarationDetailPO>> partition = Lists.partition(taxDeclarationDetailPos, 50);
                        TaxDeclarationDetailMapper mapper = sqlSession.getMapper(TaxDeclarationDetailMapper.class);
                        partition.forEach(mapper::batchUpdate);
                        sqlSession.commit();
                        log.info("finish hrsa_tax_declaration_detail");
                    }
                } catch (Exception e) {
                    sqlSession.rollback();
                    log.error("fail hrsa_tax_declaration_detail", e);
                    return 0;
                } finally {
                    sqlSession.close();
                }
                return 1;
            });
            Future<Integer> submit3 = fixedThreadPool.submit(() -> {
                SqlSession sqlSession = MyBatisFactory.sqlSessionFactory.openSession();
                try {
                    List<InsuranceSchemeDetailPO> insuranceSchemeDetailPos = getInsuranceSchemeDetailMapper().listAll();
                    if (CollectionUtils.isNotEmpty(insuranceSchemeDetailPos)) {
                        insuranceSchemeDetailPos.forEach(po -> {
                            if (OpenEnum.OFF.getValue().equals(isOpenEncrypt)) {
                                po.setUpperLimit(AESEncryptUtil.closeEncryptSetting(po.getUpperLimit(), sysConfPo));
                                po.setFixedCost(AESEncryptUtil.closeEncryptSetting(po.getFixedCost(), sysConfPo));
                                po.setLowerLimit(AESEncryptUtil.closeEncryptSetting(po.getLowerLimit(), sysConfPo));
                            } else {
                                po.setUpperLimit(AESEncryptUtil.encrypt(po.getUpperLimit()));
                                po.setFixedCost(AESEncryptUtil.encrypt(po.getFixedCost()));
                                po.setLowerLimit(AESEncryptUtil.encrypt(po.getLowerLimit()));
                            }
                        });
                        List<List<InsuranceSchemeDetailPO>> partition = Lists.partition(insuranceSchemeDetailPos, 50);
                        InsuranceSchemeDetailMapper mapper = sqlSession.getMapper(InsuranceSchemeDetailMapper.class);
                        partition.forEach(mapper::batchUpdate);
                        sqlSession.commit();
                        log.info("finish hrsa_scheme_detail");
                    }
                } catch (Exception e) {
                    sqlSession.rollback();
                    log.error("fail hrsa_scheme_detail", e);
                    return 0;
                } finally {
                    sqlSession.close();
                }
                return 1;
            });
            Future<Integer> submit4 = fixedThreadPool.submit(() -> {
                SqlSession sqlSession = MyBatisFactory.sqlSessionFactory.openSession();
                try {
                    List<InsuranceArchivesSocialSchemePO> insuranceArchivesSocialSchemePos = getSocialSchemeMapper().listAll();
                    if (CollectionUtils.isNotEmpty(insuranceArchivesSocialSchemePos)) {
                        insuranceArchivesSocialSchemePos.forEach(po -> {
                            if (OpenEnum.OFF.getValue().equals(isOpenEncrypt)) {
                                po.setSocialPaymentBaseString(AESEncryptUtil.closeEncryptSetting(po.getSocialPaymentBaseString(), sysConfPo));
                                po.setSocialPaymentComBaseString(AESEncryptUtil.closeEncryptSetting(po.getSocialPaymentComBaseString(), sysConfPo));
                            } else {
                                po.setSocialPaymentBaseString(AESEncryptUtil.encrypt(po.getSocialPaymentBaseString()));
                                po.setSocialPaymentComBaseString(AESEncryptUtil.encrypt(po.getSocialPaymentComBaseString()));
                            }
                        });
                        List<List<InsuranceArchivesSocialSchemePO>> partition = Lists.partition(insuranceArchivesSocialSchemePos, 50);
                        SocialSchemeMapper mapper = sqlSession.getMapper(SocialSchemeMapper.class);
                        partition.forEach(mapper::batchUpdate);
                        sqlSession.commit();
                        log.info("finish hrsa_social_archives");
                    }
                } catch (Exception e) {
                    sqlSession.rollback();
                    log.error("fail hrsa_social_archives", e);
                    return 0;
                } finally {
                    sqlSession.close();
                }
                return 1;
            });
            Future<Integer> submit5 = fixedThreadPool.submit(() -> {
                SqlSession sqlSession = MyBatisFactory.sqlSessionFactory.openSession();
                try {
                    List<InsuranceArchivesFundSchemePO> insuranceArchivesFundSchemePos = getFundSchemeMapper().listAll();
                    if (CollectionUtils.isNotEmpty(insuranceArchivesFundSchemePos)) {
                        insuranceArchivesFundSchemePos.forEach(po -> {
                            if (OpenEnum.OFF.getValue().equals(isOpenEncrypt)) {
                                po.setFundPaymentBaseString(AESEncryptUtil.closeEncryptSetting(po.getFundPaymentBaseString(), sysConfPo));
                                po.setFundPaymentComBaseString(AESEncryptUtil.closeEncryptSetting(po.getFundPaymentComBaseString(), sysConfPo));
                            } else {
                                po.setFundPaymentBaseString(AESEncryptUtil.encrypt(po.getFundPaymentBaseString()));
                                po.setFundPaymentComBaseString(AESEncryptUtil.encrypt(po.getFundPaymentComBaseString()));
                            }
                        });
                        List<List<InsuranceArchivesFundSchemePO>> partition = Lists.partition(insuranceArchivesFundSchemePos, 50);
                        FundSchemeMapper mapper = sqlSession.getMapper(FundSchemeMapper.class);
                        partition.forEach(mapper::batchUpdate);
                        sqlSession.commit();
                        log.info("finish hrsa_fund_archives");
                    }
                } catch (Exception e) {
                    sqlSession.rollback();
                    log.error("fail hrsa_fund_archives", e);
                    return 0;
                } finally {
                    sqlSession.close();
                }
                return 1;
            });
            Future<Integer> submit6 = fixedThreadPool.submit(() -> {
                SqlSession sqlSession = MyBatisFactory.sqlSessionFactory.openSession();
                try {
                    List<InsuranceArchivesOtherSchemePO> insuranceArchivesOtherSchemePos = getOtherSchemeMapper().listAll();
                    if (CollectionUtils.isNotEmpty(insuranceArchivesOtherSchemePos)) {
                        insuranceArchivesOtherSchemePos.forEach(po -> {
                            if (OpenEnum.OFF.getValue().equals(isOpenEncrypt)) {
                                po.setOtherPaymentBaseString(AESEncryptUtil.closeEncryptSetting(po.getOtherPaymentBaseString(), sysConfPo));
                                po.setOtherPaymentComBaseString(AESEncryptUtil.closeEncryptSetting(po.getOtherPaymentComBaseString(), sysConfPo));
                            } else {
                                po.setOtherPaymentBaseString(AESEncryptUtil.encrypt(po.getOtherPaymentBaseString()));
                                po.setOtherPaymentComBaseString(AESEncryptUtil.encrypt(po.getOtherPaymentComBaseString()));
                            }
                        });
                        List<List<InsuranceArchivesOtherSchemePO>> partition = Lists.partition(insuranceArchivesOtherSchemePos, 50);
                        OtherSchemeMapper mapper = sqlSession.getMapper(OtherSchemeMapper.class);
                        partition.forEach(mapper::batchUpdate);
                        sqlSession.commit();
                        log.info("finish hrsa_other_archives");
                    }
                } catch (Exception e) {
                    sqlSession.rollback();
                    log.error("fail hrsa_other_archives", e);
                    return 0;
                } finally {
                    sqlSession.close();
                }
                return 1;
            });
            Future<Integer> submit7 = fixedThreadPool.submit(() -> {
                SqlSession sqlSession = MyBatisFactory.sqlSessionFactory.openSession();
                try {
                    List<InsuranceAccountBatchPO> insuranceAccountBatchPos = getInsuranceAccountBatchMapper().listAll();
                    if (CollectionUtils.isNotEmpty(insuranceAccountBatchPos)) {
                        insuranceAccountBatchPos.forEach(po -> {
                            if (OpenEnum.OFF.getValue().equals(isOpenEncrypt)) {
                                po.setOtherPay(AESEncryptUtil.closeEncryptSetting(po.getOtherPay(), sysConfPo));
                                po.setSocialPay(AESEncryptUtil.closeEncryptSetting(po.getSocialPay(), sysConfPo));
                                po.setFundPay(AESEncryptUtil.closeEncryptSetting(po.getFundPay(), sysConfPo));
                            } else {
                                po.setOtherPay(AESEncryptUtil.encrypt(po.getOtherPay()));
                                po.setSocialPay(AESEncryptUtil.encrypt(po.getSocialPay()));
                                po.setFundPay(AESEncryptUtil.encrypt(po.getFundPay()));
                            }
                        });
                        List<List<InsuranceAccountBatchPO>> partition = Lists.partition(insuranceAccountBatchPos, 50);
                        InsuranceAccountBatchMapper mapper = sqlSession.getMapper(InsuranceAccountBatchMapper.class);
                        partition.forEach(mapper::batchUpdate);
                        sqlSession.commit();
                        log.info("finish hrsa_bill_batch");
                    }
                } catch (Exception e) {
                    sqlSession.rollback();
                    log.error("fail hrsa_bill_batch", e);
                    return 0;
                } finally {
                    sqlSession.close();
                }
                return 1;
            });
            Future<Integer> submit8 = fixedThreadPool.submit(() -> {
                SqlSession sqlSession = MyBatisFactory.sqlSessionFactory.openSession();
                try {
                    List<InsuranceAccountDetailPO> insuranceAccountDetailPos = getInsuranceAccountDetailMapper().listAll();
                    if (CollectionUtils.isNotEmpty(insuranceAccountDetailPos)) {
                        insuranceAccountDetailPos.forEach(po -> {
                            if (OpenEnum.OFF.getValue().equals(isOpenEncrypt)) {
                                po.setSocialPaymentBaseString(AESEncryptUtil.closeEncryptSetting(po.getSocialPaymentBaseString(), sysConfPo));
                                po.setFundPaymentBaseString(AESEncryptUtil.closeEncryptSetting(po.getFundPaymentBaseString(), sysConfPo));
                                po.setOtherPaymentBaseString(AESEncryptUtil.closeEncryptSetting(po.getOtherPaymentBaseString(), sysConfPo));
                                po.setSocialPaymentComBaseString(AESEncryptUtil.closeEncryptSetting(po.getSocialPaymentComBaseString(), sysConfPo));
                                po.setFundPaymentComBaseString(AESEncryptUtil.closeEncryptSetting(po.getFundPaymentComBaseString(), sysConfPo));
                                po.setOtherPaymentComBaseString(AESEncryptUtil.closeEncryptSetting(po.getOtherPaymentComBaseString(), sysConfPo));
                                po.setSocialPerJson(AESEncryptUtil.closeEncryptSetting(po.getSocialPerJson(), sysConfPo));
                                po.setSocialPerSum(AESEncryptUtil.closeEncryptSetting(po.getSocialPerSum(), sysConfPo));
                                po.setFundPerJson(AESEncryptUtil.closeEncryptSetting(po.getFundPerJson(), sysConfPo));
                                po.setFundPerSum(AESEncryptUtil.closeEncryptSetting(po.getFundPerSum(), sysConfPo));
                                po.setOtherPerJson(AESEncryptUtil.closeEncryptSetting(po.getOtherPerJson(), sysConfPo));
                                po.setOtherPerSum(AESEncryptUtil.closeEncryptSetting(po.getOtherPerSum(), sysConfPo));
                                po.setPerSum(AESEncryptUtil.closeEncryptSetting(po.getPerSum(), sysConfPo));
                                po.setSocialComJson(AESEncryptUtil.closeEncryptSetting(po.getSocialComJson(), sysConfPo));
                                po.setSocialComSum(AESEncryptUtil.closeEncryptSetting(po.getSocialComSum(), sysConfPo));
                                po.setComSum(AESEncryptUtil.closeEncryptSetting(po.getComSum(), sysConfPo));
                                po.setSocialSum(AESEncryptUtil.closeEncryptSetting(po.getSocialSum(), sysConfPo));
                                po.setFundSum(AESEncryptUtil.closeEncryptSetting(po.getFundSum(), sysConfPo));
                                po.setOtherSum(AESEncryptUtil.closeEncryptSetting(po.getOtherSum(), sysConfPo));
                                po.setTotal(AESEncryptUtil.closeEncryptSetting(po.getTotal(), sysConfPo));
                            } else {
                                po.setSocialPaymentBaseString(AESEncryptUtil.encrypt(po.getSocialPaymentBaseString()));
                                po.setFundPaymentBaseString(AESEncryptUtil.encrypt(po.getFundPaymentBaseString()));
                                po.setOtherPaymentBaseString(AESEncryptUtil.encrypt(po.getOtherPaymentBaseString()));
                                po.setSocialPaymentComBaseString(AESEncryptUtil.encrypt(po.getSocialPaymentComBaseString()));
                                po.setFundPaymentComBaseString(AESEncryptUtil.encrypt(po.getFundPaymentComBaseString()));
                                po.setOtherPaymentComBaseString(AESEncryptUtil.encrypt(po.getOtherPaymentComBaseString()));
                                po.setSocialPerJson(AESEncryptUtil.encrypt(po.getSocialPerJson()));
                                po.setSocialPerSum(AESEncryptUtil.encrypt(po.getSocialPerSum()));
                                po.setFundPerJson(AESEncryptUtil.encrypt(po.getFundPerJson()));
                                po.setFundPerSum(AESEncryptUtil.encrypt(po.getFundPerSum()));
                                po.setOtherPerJson(AESEncryptUtil.encrypt(po.getOtherPerJson()));
                                po.setOtherPerSum(AESEncryptUtil.encrypt(po.getOtherPerSum()));
                                po.setPerSum(AESEncryptUtil.encrypt(po.getPerSum()));
                                po.setSocialComJson(AESEncryptUtil.encrypt(po.getSocialComJson()));
                                po.setSocialComSum(AESEncryptUtil.encrypt(po.getSocialComSum()));
                                po.setComSum(AESEncryptUtil.encrypt(po.getComSum()));
                                po.setSocialSum(AESEncryptUtil.encrypt(po.getSocialSum()));
                                po.setFundSum(AESEncryptUtil.encrypt(po.getFundSum()));
                                po.setOtherSum(AESEncryptUtil.encrypt(po.getOtherSum()));
                                po.setTotal(AESEncryptUtil.encrypt(po.getTotal()));
                            }
                        });
                        List<List<InsuranceAccountDetailPO>> partition = Lists.partition(insuranceAccountDetailPos, 20);
                        InsuranceAccountDetailMapper mapper = sqlSession.getMapper(InsuranceAccountDetailMapper.class);
                        partition.forEach(mapper::batchUpdate);
                        sqlSession.commit();
                        log.info("finish hrsa_bill_detail");
                    }
                } catch (Exception e) {
                    sqlSession.rollback();
                    log.error("fail hrsa_bill_detail", e);
                    return 0;
                } finally {
                    sqlSession.close();
                }
                return 1;
            });
            Future<Integer> submit9 = fixedThreadPool.submit(() -> {
                SqlSession sqlSession = MyBatisFactory.sqlSessionFactory.openSession();
                try {
                    List<SalaryArchiveItemPO> salaryArchiveItemPos = getSalaryArchiveItemMapper().listAll();
                    if (CollectionUtils.isNotEmpty(salaryArchiveItemPos)) {
                        salaryArchiveItemPos.forEach(po -> {
                            if (OpenEnum.OFF.getValue().equals(isOpenEncrypt)) {
                                po.setItemValue(AESEncryptUtil.closeEncryptSetting(po.getItemValue(), sysConfPo));
                            } else {
                                po.setItemValue(AESEncryptUtil.encrypt(po.getItemValue()));
                            }
                        });
                        List<List<SalaryArchiveItemPO>> partition = Lists.partition(salaryArchiveItemPos, 50);
                        SalaryArchiveItemMapper mapper = sqlSession.getMapper(SalaryArchiveItemMapper.class);
                        partition.forEach(mapper::batchUpdate);
                        sqlSession.commit();
                        log.info("finish hrsa_salary_archive_item");
                    }
                } catch (Exception e) {
                    sqlSession.rollback();
                    log.error("fail hrsa_salary_archive_item", e);
                    return 0;
                } finally {
                    sqlSession.close();
                }
                return 1;
            });
            Future<Integer> submit10 = fixedThreadPool.submit(() -> {
                SqlSession sqlSession = MyBatisFactory.sqlSessionFactory.openSession();
                try {
                    List<AddUpDeduction> addUpDeductions = getAddUpDeductionMapper().listAll();
                    if (CollectionUtils.isNotEmpty(addUpDeductions)) {
                        addUpDeductions.forEach(po -> {
                            if (OpenEnum.OFF.getValue().equals(isOpenEncrypt)) {
                                encryptUtil.decrypt(po, AddUpDeduction.class);
                            } else {
                                encryptUtil.encrypt(po, AddUpDeduction.class);
                            }
                        });
                        List<List<AddUpDeduction>> partition = Lists.partition(addUpDeductions, 50);
                        AddUpDeductionMapper mapper = sqlSession.getMapper(AddUpDeductionMapper.class);
                        partition.forEach(mapper::updateData);
                        sqlSession.commit();
                        log.info("finish hrsa_add_up_deduction");
                    }
                } catch (Exception e) {
                    sqlSession.rollback();
                    log.error("fail hrsa_add_up_deduction", e);
                    return 0;
                } finally {
                    sqlSession.close();
                }
                return 1;
            });
            Future<Integer> submit11 = fixedThreadPool.submit(() -> {
                SqlSession sqlSession = MyBatisFactory.sqlSessionFactory.openSession();
                try {
                    List<OtherDeductionPO> otherDeductionPos = getOtherDeductionMapper().listSome(new OtherDeductionPO());
                    if (CollectionUtils.isNotEmpty(otherDeductionPos)) {
                        otherDeductionPos.forEach(po -> {
                            if (OpenEnum.OFF.getValue().equals(isOpenEncrypt)) {
                                po.setBusinessHealthyInsurance(AESEncryptUtil.closeEncryptSetting(po.getBusinessHealthyInsurance(), sysConfPo));
                                po.setTaxDelayEndowmentInsurance(AESEncryptUtil.closeEncryptSetting(po.getTaxDelayEndowmentInsurance(), sysConfPo));
                                po.setOtherDeduction(AESEncryptUtil.closeEncryptSetting(po.getOtherDeduction(), sysConfPo));
                                po.setDeductionAllowedDonation(AESEncryptUtil.closeEncryptSetting(po.getDeductionAllowedDonation(), sysConfPo));
                                po.setPrivatePension(AESEncryptUtil.closeEncryptSetting(po.getPrivatePension(), sysConfPo));
                            } else {
                                po.setBusinessHealthyInsurance(AESEncryptUtil.encrypt(po.getBusinessHealthyInsurance()));
                                po.setTaxDelayEndowmentInsurance(AESEncryptUtil.encrypt(po.getTaxDelayEndowmentInsurance()));
                                po.setOtherDeduction(AESEncryptUtil.encrypt(po.getOtherDeduction()));
                                po.setDeductionAllowedDonation(AESEncryptUtil.encrypt(po.getDeductionAllowedDonation()));
                                po.setPrivatePension(AESEncryptUtil.encrypt(po.getPrivatePension()));
                            }
                        });
                        List<List<OtherDeductionPO>> partition = Lists.partition(otherDeductionPos, 50);
                        OtherDeductionMapper mapper = sqlSession.getMapper(OtherDeductionMapper.class);
                        partition.forEach(mapper::updateData);
                        sqlSession.commit();
                        log.info("finish hrsa_other_deduction");
                    }
                } catch (Exception e) {
                    sqlSession.rollback();
                    log.error("fail hrsa_other_deduction", e);
                    return 0;
                } finally {
                    sqlSession.close();
                }
                return 1;
            });
            Future<Integer> submit12 = fixedThreadPool.submit(() -> {
                SqlSession sqlSession = MyBatisFactory.sqlSessionFactory.openSession();
                try {
                    List<AddUpSituation> addUpSituations = getAddUpSituationMapper().listAll();
                    if (CollectionUtils.isNotEmpty(addUpSituations)) {
                        addUpSituations.forEach(po -> {
                            if (OpenEnum.OFF.getValue().equals(isOpenEncrypt)) {
                                po.setAddUpIncome(AESEncryptUtil.closeEncryptSetting(po.getAddUpIncome(), sysConfPo));
                                po.setAddUpSubtraction(AESEncryptUtil.closeEncryptSetting(po.getAddUpSubtraction(), sysConfPo));
                                po.setAddUpSocialSecurityTotal(AESEncryptUtil.closeEncryptSetting(po.getAddUpSocialSecurityTotal(), sysConfPo));
                                po.setAddUpAccumulationFundTotal(AESEncryptUtil.closeEncryptSetting(po.getAddUpAccumulationFundTotal(), sysConfPo));
                                po.setAddUpChildEducation(AESEncryptUtil.closeEncryptSetting(po.getAddUpChildEducation(), sysConfPo));
                                po.setAddUpContinuingEducation(AESEncryptUtil.closeEncryptSetting(po.getAddUpContinuingEducation(), sysConfPo));
                                po.setAddUpHousingLoanInterest(AESEncryptUtil.closeEncryptSetting(po.getAddUpHousingLoanInterest(), sysConfPo));
                                po.setAddUpHousingRent(AESEncryptUtil.closeEncryptSetting(po.getAddUpHousingRent(), sysConfPo));
                                po.setAddUpSupportElderly(AESEncryptUtil.closeEncryptSetting(po.getAddUpSupportElderly(), sysConfPo));
                                po.setAddUpEnterpriseAndOther(AESEncryptUtil.closeEncryptSetting(po.getAddUpEnterpriseAndOther(), sysConfPo));
                                po.setAddUpOtherDeduction(AESEncryptUtil.closeEncryptSetting(po.getAddUpOtherDeduction(), sysConfPo));
                                po.setAddUpTaxExemptIncome(AESEncryptUtil.closeEncryptSetting(po.getAddUpTaxExemptIncome(), sysConfPo));
                                po.setAddUpAllowedDonation(AESEncryptUtil.closeEncryptSetting(po.getAddUpAllowedDonation(), sysConfPo));
                                po.setAddUpAdvanceTax(AESEncryptUtil.closeEncryptSetting(po.getAddUpAdvanceTax(), sysConfPo));
                                po.setAddUpIllnessMedical(AESEncryptUtil.closeEncryptSetting(po.getAddUpIllnessMedical(), sysConfPo));
                                po.setAddUpTaxSavings(AESEncryptUtil.closeEncryptSetting(po.getAddUpTaxSavings(), sysConfPo));
                                po.setAddUpInfantCare(AESEncryptUtil.closeEncryptSetting(po.getAddUpInfantCare(), sysConfPo));
                                po.setAddUpPrivatePension(AESEncryptUtil.closeEncryptSetting(po.getAddUpPrivatePension(), sysConfPo));
                            } else {
                                po.setAddUpIncome(AESEncryptUtil.encrypt(po.getAddUpIncome()));
                                po.setAddUpSubtraction(AESEncryptUtil.encrypt(po.getAddUpSubtraction()));
                                po.setAddUpSocialSecurityTotal(AESEncryptUtil.encrypt(po.getAddUpSocialSecurityTotal()));
                                po.setAddUpAccumulationFundTotal(AESEncryptUtil.encrypt(po.getAddUpAccumulationFundTotal()));
                                po.setAddUpChildEducation(AESEncryptUtil.encrypt(po.getAddUpChildEducation()));
                                po.setAddUpContinuingEducation(AESEncryptUtil.encrypt(po.getAddUpContinuingEducation()));
                                po.setAddUpHousingLoanInterest(AESEncryptUtil.encrypt(po.getAddUpHousingLoanInterest()));
                                po.setAddUpHousingRent(AESEncryptUtil.encrypt(po.getAddUpHousingRent()));
                                po.setAddUpSupportElderly(AESEncryptUtil.encrypt(po.getAddUpSupportElderly()));
                                po.setAddUpEnterpriseAndOther(AESEncryptUtil.encrypt(po.getAddUpEnterpriseAndOther()));
                                po.setAddUpOtherDeduction(AESEncryptUtil.encrypt(po.getAddUpOtherDeduction()));
                                po.setAddUpTaxExemptIncome(AESEncryptUtil.encrypt(po.getAddUpTaxExemptIncome()));
                                po.setAddUpAllowedDonation(AESEncryptUtil.encrypt(po.getAddUpAllowedDonation()));
                                po.setAddUpAdvanceTax(AESEncryptUtil.encrypt(po.getAddUpAdvanceTax()));
                                po.setAddUpIllnessMedical(AESEncryptUtil.encrypt(po.getAddUpIllnessMedical()));
                                po.setAddUpTaxSavings(AESEncryptUtil.encrypt(po.getAddUpTaxSavings()));
                                po.setAddUpInfantCare(AESEncryptUtil.encrypt(po.getAddUpInfantCare()));
                                po.setAddUpPrivatePension(AESEncryptUtil.encrypt(po.getAddUpPrivatePension()));
                            }
                        });
                        List<List<AddUpSituation>> partition = Lists.partition(addUpSituations, 50);
                        AddUpSituationMapper mapper = sqlSession.getMapper(AddUpSituationMapper.class);
                        partition.forEach(mapper::updateData);
                        sqlSession.commit();
                        log.info("finish hrsa_add_up_situation");
                    }
                } catch (Exception e) {
                    sqlSession.rollback();
                    log.error("fail hrsa_add_up_situation", e);
                    return 0;
                } finally {
                    sqlSession.close();
                }
                return 1;
            });
            Future<Integer> submit13 = fixedThreadPool.submit(() -> {
                SqlSession sqlSession = MyBatisFactory.sqlSessionFactory.openSession();
                try {
                    List<SpecialAddDeductionPO> addUpSituations = getSpecialAddDeductionMapper().listAll();
                    if (CollectionUtils.isNotEmpty(addUpSituations)) {
                        addUpSituations.forEach(po -> {
                            if (OpenEnum.OFF.getValue().equals(isOpenEncrypt)) {
                                encryptUtil.decrypt(po, SpecialAddDeductionPO.class);
                            } else {
                                encryptUtil.encrypt(po, SpecialAddDeductionPO.class);
                            }
                        });
                        List<List<SpecialAddDeductionPO>> partition = Lists.partition(addUpSituations, 50);
                        SpecialAddDeductionMapper mapper = sqlSession.getMapper(SpecialAddDeductionMapper.class);
                        partition.forEach(mapper::updateBatchSelective);
                        sqlSession.commit();
                        log.info("finish hrsa_special_add_deduction");
                    }
                } catch (Exception e) {
                    sqlSession.rollback();
                    log.error("fail hrsa_special_add_deduction", e);
                    return 0;
                } finally {
                    sqlSession.close();
                }
                return 1;
            });

            Future<Integer> submit14 = fixedThreadPool.submit(() -> {
                SqlSession sqlSession = MyBatisFactory.sqlSessionFactory.openSession();
                try {
                    List<ExcelInsuranceDetailPO> excelInsuranceDetailPOS = getExcelInsuranceDetailMapper().listAll();
                    if (CollectionUtils.isNotEmpty(excelInsuranceDetailPOS)) {
                        excelInsuranceDetailPOS.forEach(po -> {
                            if (OpenEnum.OFF.getValue().equals(isOpenEncrypt)) {
                                po.setSocialPaymentBaseString(AESEncryptUtil.closeEncryptSetting(po.getSocialPaymentBaseString(), sysConfPo));
                                po.setSocialPaymentComBaseString(AESEncryptUtil.closeEncryptSetting(po.getSocialPaymentComBaseString(), sysConfPo));
                                po.setFundPaymentBaseString(AESEncryptUtil.closeEncryptSetting(po.getFundPaymentBaseString(), sysConfPo));
                                po.setFundPaymentComBaseString(AESEncryptUtil.closeEncryptSetting(po.getFundPaymentComBaseString(), sysConfPo));
                                po.setOtherPaymentBaseString(AESEncryptUtil.closeEncryptSetting(po.getOtherPaymentBaseString(), sysConfPo));
                                po.setOtherPaymentComBaseString(AESEncryptUtil.closeEncryptSetting(po.getOtherPaymentComBaseString(), sysConfPo));
                                po.setSocialPerJson(AESEncryptUtil.closeEncryptSetting(po.getSocialPerJson(), sysConfPo));
                                po.setSocialPerSum(AESEncryptUtil.closeEncryptSetting(po.getSocialPerSum(), sysConfPo));
                                po.setFundPerJson(AESEncryptUtil.closeEncryptSetting(po.getFundPerJson(), sysConfPo));
                                po.setFundPerSum(AESEncryptUtil.closeEncryptSetting(po.getFundPerSum(), sysConfPo));
                                po.setOtherPerJson(AESEncryptUtil.closeEncryptSetting(po.getOtherPerJson(), sysConfPo));
                                po.setOtherPerSum(AESEncryptUtil.closeEncryptSetting(po.getOtherPerSum(), sysConfPo));
                                po.setPerSum(AESEncryptUtil.closeEncryptSetting(po.getPerSum(), sysConfPo));
                                po.setSocialComJson(AESEncryptUtil.closeEncryptSetting(po.getSocialComJson(), sysConfPo));
                                po.setSocialComSum(AESEncryptUtil.closeEncryptSetting(po.getSocialComSum(), sysConfPo));
                                po.setComSum(AESEncryptUtil.closeEncryptSetting(po.getComSum(), sysConfPo));
                                po.setSocialSum(AESEncryptUtil.closeEncryptSetting(po.getSocialSum(), sysConfPo));
                                po.setFundSum(AESEncryptUtil.closeEncryptSetting(po.getFundSum(), sysConfPo));
                                po.setOtherSum(AESEncryptUtil.closeEncryptSetting(po.getOtherSum(), sysConfPo));
                                po.setTotal(AESEncryptUtil.closeEncryptSetting(po.getTotal(), sysConfPo));
                            } else {
                                po.setSocialPaymentBaseString(AESEncryptUtil.encrypt(po.getSocialPaymentBaseString()));
                                po.setSocialPaymentComBaseString(AESEncryptUtil.encrypt(po.getSocialPaymentComBaseString()));
                                po.setFundPaymentBaseString(AESEncryptUtil.encrypt(po.getFundPaymentBaseString()));
                                po.setFundPaymentComBaseString(AESEncryptUtil.encrypt(po.getFundPaymentComBaseString()));
                                po.setOtherPaymentBaseString(AESEncryptUtil.encrypt(po.getOtherPaymentBaseString()));
                                po.setOtherPaymentComBaseString(AESEncryptUtil.encrypt(po.getOtherPaymentComBaseString()));
                                po.setSocialPerJson(AESEncryptUtil.encrypt(po.getSocialPerJson()));
                                po.setSocialPerSum(AESEncryptUtil.encrypt(po.getSocialPerSum()));
                                po.setFundPerJson(AESEncryptUtil.encrypt(po.getFundPerJson()));
                                po.setFundPerSum(AESEncryptUtil.encrypt(po.getFundPerSum()));
                                po.setOtherPerJson(AESEncryptUtil.encrypt(po.getOtherPerJson()));
                                po.setOtherPerSum(AESEncryptUtil.encrypt(po.getOtherPerSum()));
                                po.setPerSum(AESEncryptUtil.encrypt(po.getPerSum()));
                                po.setSocialComJson(AESEncryptUtil.encrypt(po.getSocialComJson()));
                                po.setSocialComSum(AESEncryptUtil.encrypt(po.getSocialComSum()));
                                po.setComSum(AESEncryptUtil.encrypt(po.getComSum()));
                                po.setSocialSum(AESEncryptUtil.encrypt(po.getSocialSum()));
                                po.setFundSum(AESEncryptUtil.encrypt(po.getFundSum()));
                                po.setOtherSum(AESEncryptUtil.encrypt(po.getOtherSum()));
                                po.setTotal(AESEncryptUtil.encrypt(po.getTotal()));
                            }
                        });
                        List<List<ExcelInsuranceDetailPO>> partition = Lists.partition(excelInsuranceDetailPOS, 10);
                        ExcelInsuranceDetailMapper mapper = sqlSession.getMapper(ExcelInsuranceDetailMapper.class);
                        partition.forEach(mapper::updateBatchSelective);
                        sqlSession.commit();
                        log.info("finish hrsa_excel_bill_detail");
                    }
                } catch (Exception e) {
                    sqlSession.rollback();
                    log.error("fail hrsa_excel_bill_detail", e);
                    return 0;
                } finally {
                    sqlSession.close();
                }
                return 1;
            });

            Future<Integer> submit15 = fixedThreadPool.submit(() -> {
                SqlSession sqlSession = MyBatisFactory.sqlSessionFactory.openSession();
                try {
                    List<VariableArchiveItemPO> variableArchiveItemPOS = getVariableArchiveItemService(user).listAll();
                    if (CollectionUtils.isNotEmpty(variableArchiveItemPOS)) {
                        variableArchiveItemPOS.forEach(po -> {
                            if (OpenEnum.OFF.getValue().equals(isOpenEncrypt)) {
                                po.setItemValue(AESEncryptUtil.closeEncryptSetting(po.getItemValue(), sysConfPo));
                            } else {
                                po.setItemValue(AESEncryptUtil.encrypt(po.getItemValue()));
                            }
                        });
                        List<List<VariableArchiveItemPO>> partition = Lists.partition(variableArchiveItemPOS, 10);
                        VariableArchiveItemMapper mapper = sqlSession.getMapper(VariableArchiveItemMapper.class);
                        partition.forEach(mapper::updateBatchSelective);
                        sqlSession.commit();
                        log.info("finish hrsa_variable_archive_item");
                    }
                } catch (Exception e) {
                    sqlSession.rollback();
                    log.error("fail hrsa_variable_archive_item", e);
                    return 0;
                } finally {
                    sqlSession.close();
                }
                return 1;
            });

            int flag = submit.get() + submit1.get() + submit2.get() + submit3.get() + submit4.get() + submit5.get() + submit6.get() + submit7.get() + submit8.get() + submit9.get() + submit10.get() + submit11.get() + submit12.get() + submit13.get() + submit14.get() + submit15.get();
            if (flag == 16) {
                Util_DataCache.setObjVal(ENCRYPT_IN_PROGRESS + progressId, "success", 30);
            } else {
                Util_DataCache.setObjVal(ENCRYPT_IN_PROGRESS + progressId, "fail", 30);
            }
            Util_DataCache.clearVal(AES_ENCRYPT_IN_PROGRESS);
            return flag == 16;
        } catch (Exception e) {
            Util_DataCache.setObjVal(ENCRYPT_IN_PROGRESS + progressId, "fail", 30);
            Util_DataCache.clearVal(AES_ENCRYPT_IN_PROGRESS);
            log.error("应用设置加解密数据异常", e);
            return false;
        } finally {
            Util_DataCache.clearVal(AES_ENCRYPT_IN_PROGRESS);
        }
    }
}
